<template>
  <section>
    <!-- 工具条 高级查询 -->
    <el-col :span="24" class="toolbar" style="padding-bottom: 0px;">
      <el-form :inline="true">
        <el-form-item>
          <el-input v-model="keyword" placeholder="请输入关键字"></el-input>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" v-on:click="keywordQuery" v-perm="'department:list'">查询</el-button>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleAdd" v-perm="'department:save'">新增</el-button>
        </el-form-item>
      </el-form>
    </el-col>

    <!--列表-->
    <!--
      :data="departments" - 列表数据
      highlight-current-row v-loading="listLoading" - 当前行高亮
      @selection-change="selsChange" - 选项改变就是触发
      v-loading="listLoading" - 记载框
    -->
    <el-table :data="departments" highlight-current-row v-loading="listLoading" @selection-change="selsChange"
              style="width: 100%;">
      <el-table-column type="selection" width="55">
      </el-table-column>
      <el-table-column type="index" width="60">
      </el-table-column>
      <el-table-column prop="sn" label="部门编号" width="120" sortable>
      </el-table-column>
      <el-table-column prop="name" label="部门名称" width="100" sortable>
      </el-table-column>
      <el-table-column prop="dirPath" label="路径" width="100" sortable>
      </el-table-column>
      <el-table-column prop="state" label="状态" width="120" sortable>
        <template scope="scope">
          <span v-if="scope.row.state==0" style="color: red">禁用</span>
          <span v-else style="color: green">启用</span>
        </template>
      </el-table-column>
      <el-table-column prop="employee.username" label="部门经理" width="120" sortable>
      </el-table-column>
      <el-table-column prop="department.name" label="上级部门" width="120" sortable>
      </el-table-column>
      <el-table-column label="操作">
        <template scope="scope">
          <el-button size="small" v-perm="'department:save'" @click="handleEdit(scope.$index, scope.row)">修改</el-button>
          <el-button type="danger" v-perm="'department:delete'" size="small" @click="handleDel(scope.$index, scope.row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <!--工具条-->
    <el-col :span="24" class="toolbar">
      <el-button type="danger" v-perm="'department:patchDel'" @click="batchRemove" :disabled="this.sels.length===0">批量删除</el-button>
      <el-pagination @current-change="handleCurrentChange"
                     background
                     layout="prev, pager, next"
                     :page-size="pageSize"
                     :total="totals"
                     :current-page="currentPage" style="float:right;">
      </el-pagination>
    </el-col>

    <!--添加或修改界面-->
    <!--
          title="添加或修改" - 标题
          :visible.sync="saveFormVisible" - 控制当前对话框是否显示 - 默认为false不显示
          :close-on-click-modal="false" - 点击对话框以外的区域不关闭
    -->
    <el-dialog :title="title" :visible.sync="saveFormVisible" :close-on-click-modal="false">
      <!--
            :model="saveForm"  - 表单绑定模型数据对象saveForm
            label-width="80px"  - 标签的宽度
            :rules="saveFormRules" - 验证规则 - 表单项校验
            ref="saveForm" - 为当前对话框取名saveForm - 做表单校验

            label="姓名" - 标签名字
            prop="name" - 要做校验的时候必须要，不做校验就没有必要
            v-model="saveForm.name" - 双向绑定
            auto-complete="off" - 自动完成 - 关闭
      -->
      <el-form :model="saveForm" label-width="80px" :rules="saveFormRules" ref="saveForm">
        <el-form-item label="部门编号" prop="sn">
          <el-input v-model="saveForm.sn" auto-complete="off"></el-input>
        </el-form-item>
        <el-form-item label="部门名称" prop="name">
          <el-input v-model="saveForm.name" auto-complete="off"></el-input>
        </el-form-item>
        <el-form-item label="状态">
          <el-radio-group v-model="saveForm.state">
            <el-radio class="radio" :label="1">启用</el-radio>
            <el-radio class="radio" :label="0">禁用</el-radio>
          </el-radio-group>
        </el-form-item>
        <!--
          select - 选择框
          v-model="saveForm.manager_id" - 双向绑定
          v-for="item in managers"   - item就是每一个经理对象 - employee对象

          :label="item.username" - 回显哪一个属性值【经理的名称】
          :value="item.id" - 传递哪个属性值【经理的id】
        -->
        <el-form-item label="部门经理">
          <el-select v-model="saveForm.manager_id" placeholder="请选择">
            <el-option v-for="item in managers"
                       :label="item.username"
                       :value="item.id">
              <span style="float: left">{{item.username }}</span>
              <span style="float: right; color: #8492a6; font-size: 13px">{{item.phone }}</span>
            </el-option>
          </el-select><el-form-item label="上级部门">
          <el-cascader v-model="saveForm.parent_id"
                       :options="deptTree"
                       :props="{
                checkStrictly: true,
                label: 'name',
                value: 'id'
              }"
                       clearable>
          </el-cascader>
        </el-form-item>
        </el-form-item>

      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click.native="saveFormVisible = false">取消</el-button>
        <el-button type="primary" @click.native="saveSubmit" :loading="saveLoading">提交</el-button>
      </div>
    </el-dialog>

  </section>
</template>

<script>
import util from '../../common/js/util'
//import NProgress from 'nprogress'
import {
  getDepartmentListPage,
  removeDepartment,
  batchRemoveDepartment,
  editDepartment,
  addDepartment
} from '../../api/api';

export default {
  data() {
    return {
      //1.分页查询的相关参数
      departments: [],  //列表数据
      pageSize: 5,      //每页显示的条数
      currentPage: 1,   //当前页
      totals: 0,        //总数量
      listLoading: false, //加载框

      //2.高级查询的相关参数
      keyword: "",

      //3.批量删除的相关数据
      sels: [],//列表选中列

      //4.添加或修改相关数据
      title: '',
      saveFormVisible: false,//对话框界面是否显示 - 默认不显示
      saveLoading: false,//保存的加载框 - 默认不显示
      saveFormRules: {//表单项验证
        sn: [
          {required: true, message: '请输入部门编号', trigger: 'blur'}
        ],
        name: [
          {required: true, message: '请输入部门名称', trigger: 'blur'}
        ]
      },
      //添加或修改界面数据
      saveForm: {
        id: null,
        sn: '',
        name: '',
        state: 1,
        parent_id: null,
        manager_id: null
      },
      //所有经理信息
      managers: [],
      //显示部门树
      deptTree: []

    }
  },
  methods: {
    //1.获取部门列表
    getDepartments() {
      let para = {
        currentPage: this.currentPage,
        pageSize: this.pageSize,
        keyword: this.keyword
      };
      this.listLoading = true; //显示加载框
      this.$http.post("/department", para).then(res => {
        this.departments = res.data.data;//给数组赋值， 显示列表数据
        this.totals = res.data.totals;  //给总数量赋值， 计算分页栏
        this.listLoading = false;//关闭加载框
      }).catch(res => {
        this.$message.error("系统繁忙，请稍后重试!!!");
      })
    },
    //2.分页实现
    handleCurrentChange(val) {
      this.currentPage = val;
      this.getDepartments();
    },
    //3.高级查询实现
    keywordQuery() {
      //防止当前页不在第一页的时候，通过关键字查询，当前页没有数据
      this.currentPage = 1;
      this.getDepartments();
    },
    //4.删除功能实现
    handleDel: function (index, row) {
      //elementUI提供的模态框 - 点击确认执行then里面的代码，取消执行catch
      this.$confirm('确认删除该记录吗?', '提示', {
        type: 'warning'
      }).then(() => {
        this.listLoading = true;
        this.$http.delete("/department/" + row.id).then(res => {
          this.listLoading = false;
          if (res.data.success) {
            this.$message.success("删除成功");
            //删除成功后对当前页的处理
            var totalPage = Math.ceil(this.totals/this.pageSize);//总页数-最后一页
            if(this.currentPage==totalPage && (this.totals-1)%this.pageSize==0 && this.currentPage!=1){
              this.currentPage--;
            }
            this.getDepartments();
          } else {
            this.$message.error("系统繁忙，请稍后重试!!![500]")
          }
        }).catch(res => {
          this.$message.error("系统繁忙，请稍后重试!!![404]")
        })
        /*this.listLoading = true;
        //NProgress.start();
        let para = {id: row.id};
        removeDepartment(para).then((res) => {
          this.listLoading = false;
          //NProgress.done();
          this.$message({
            message: '删除成功',
            type: 'success'
          });
          this.getDepartments();
        });*/
      }).catch(() => {

      });
    },
    //5.
    selsChange: function (sels) {
      this.sels = sels;
    },
    //6.批量删除
    batchRemove: function () {
      //获取数组中每一个对象的id 并形成新的数组
      var ids = this.sels.map(item => item.id);//.toString()
      this.$confirm('确认删除选中记录吗？', '提示', {
        type: 'warning'
      }).then(() => {
        this.listLoading = true; //显示加载框
        this.$http.patch("/department", ids).then(res => {
          this.listLoading = false; //隐藏加载框
          if (res.data.success) { //操作成功
            this.$message.success("删除成功");
            var totalPage = Math.ceil(this.totals/this.pageSize);//总页数-最后一页
            if(this.currentPage==totalPage && (this.totals-ids.length)%this.pageSize==0 && this.currentPage!=1){
              this.currentPage--;
            }
            this.getDepartments();
          } else { //操作失败
            this.$message.error("系统繁忙，请稍后重试!!![500]"); //后端500错误走这里
          }
        }).catch(res => {
          this.$message.error("系统繁忙，请稍后重试!!![400,404]");
        })
      }).catch(() => {

      });
    },

    //7.点击修改按钮弹出对话框
    handleEdit: function (index, row) {
      this.title = "修改";
      this.saveFormVisible = true;//弹出对话框
      //回显数据：创建一个空对象{}，将row中的数据拷贝给{}
      this.saveForm = Object.assign({}, row);
      this.getManagers();
      this.getDeptTree();
    },
    //8.点击新增按钮弹出对话框
    handleAdd: function () {
      this.title = "新增";
      this.saveFormVisible = true;
      this.saveForm = {
        id: null,
        sn: '',
        name: '',
        state: 1,
        parent_id: null,
        manager_id: null
      };
      this.getManagers();
      this.getDeptTree();
    },
    //9.新增或修改数据提交到后端
    saveSubmit: function () {
      this.$refs.saveForm.validate((valid) => {
        if (valid) {
          this.$confirm('确认提交吗？', '提示', {}).then(() => {
            this.saveLoading = true;
            let para = Object.assign({}, this.saveForm);
            //1.不修改部门，不点击级联狂
            //2.不修改上级部门，点了级联框选过其他部门
            //3.
            //4.
            //5.
            var isArr = para.parent_id;
            if (Array.isArray(isArr)){
              if(isArr.length == 0){
                para.parent_id = null;
              }else {
                para.parent_id = isArr[isArr.length-1]
              }
            }
            this.$http.put("/department", para).then(res => {
              this.saveLoading = false;//关闭加载框
              this.saveFormVisible = false;//关闭对话框
              if (res.data.success) { //操作成功
                this.getDepartments();
              } else { //操作失败
                this.$message.error("系统繁忙，请稍后重试!!![500]"); //后端500错误走这里
              }
            }).catch(res => {
              this.$message.error("系统繁忙，请稍后重试!!![400,404]");
            })
            /*  this.editLoading = true;
            //NProgress.start();
            let para = Object.assign({}, this.editForm);
            para.birth = (!para.birth || para.birth == '') ? '' : util.formatDate.format(new Date(para.birth), 'yyyy-MM-dd');
            editDepartment(para).then((res) => {
              this.editLoading = false;
              //NProgress.done();
              this.$message({
                message: '提交成功',
                type: 'success'
              });
              this.$refs['editForm'].resetFields();
              this.editFormVisible = false;
              this.getDepartments();
            });*/
          });
        }
      });
    },
    //10.获取所有的部门经理 - 员工
    getManagers(){
      this.$http.get("/employee").then(res=>{
        this.managers = res.data;
      })
    },
    //11.获取部门树
    getDeptTree(){
      this.$http.get("/department/deptTree").then(res=>{
        this.deptTree = res.data;
      })
    }

  },
  mounted() {
    this.getDepartments();
  }
}

</script>

<style scoped>

</style>